package com.jing.yao.security;

import com.jing.yao.utils.CryptoUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;

/**
 * 重写UsernamePasswordAuthenticationFilter，对用户名密码进行解密
 *
 * @author lr
 * @since 2020-07-28
 */
public class YaoUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public YaoUsernamePasswordAuthenticationFilter(final AuthenticationManager authenticationManager,
                                                   AuthenticationSuccessHandler successHandler,
                                                   AuthenticationFailureHandler failureHandler) {
        this.setAuthenticationManager(authenticationManager);
        this.setAuthenticationSuccessHandler(successHandler);
        this.setAuthenticationFailureHandler(failureHandler);
    }

    /**
     * 重写获取用户，解密
     *
     * @param request
     * @return
     */
    @Override
    protected String obtainUsername(HttpServletRequest request) {
        String username = super.obtainUsername(request);
        try {
            username = CryptoUtils.desEncrypt(username);
        } catch (Exception e) {
            logger.error("用户名解密失败", e);
            username = "";
        }
        username = username.trim();
        return username;
    }

    /**
     * 重写获取密码，解密
     *
     * @param request
     * @return
     */
    @Override
    protected String obtainPassword(HttpServletRequest request) {
        String password = super.obtainPassword(request);
        try {
            password = CryptoUtils.desEncrypt(password);
        } catch (Exception e) {
            logger.error("密码解密失败", e);
            password = "";
        }
        password = password.trim();
        return password;
    }
}
